# coding=utf-8
# __author__ = "James Zhang"
# !/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import json
import time
import tornado.locale
import tornado.web
import tornado.websocket
from tornado import httputil

from core.sessions.backends.db import SessionStore, Session
from core.utils.http import cookie_date
from core.utils import encoders
from core.conf import settings
from core.cache import cache as _cache
from core.cache import close_caches


class BaseHandler(tornado.web.RequestHandler):
    """
        基础Hanlder类
    """

    def initialize(self):
        super(BaseHandler, self).initialize()
        self._headers = httputil.HTTPHeaders({
            'Server': self.application._server_name,
            "Content-Type": "text/html; charset=UTF-8",
            "Date": httputil.format_timestamp(time.time()),
        })
        self.context = {}
        self._token = self.get_cookie(self.application._cookie_name, None)  # 从客户端得到sessionid
        self.session = self.__get_session(self._token)             # 创建一个session对象
        self.set_cookie(self.application._cookie_name, self.session.session_key)  # 设置sessionid

    @property
    def cache(self):
        """

        缓存相关的处理动作, 待以后更新!!!

        :return:
        """
        return _cache

    @property
    def db(self):
        """
        数据库连接相关的操作

        可能不需要
        :return:
        """
        return Session.db

    def render(self, template_name, **kwargs):

        if not kwargs:
            kwargs = self.context
        super(BaseHandler, self).render(template_name, **kwargs)

    def get_current_user(self):
        """
            这里应该返回一个user Object
        :return:
        """
        # return self.session.get('current_user', None)
        pass

    def get_current_username(self):
        """
        返回当前user的用户名
        :return:
        """
        return self.session.get('username', '')

    @property
    def current_user(self):
        """
        需复写基础类的方法
        :return:
        """
        return self.get_current_user()

    def get_user_locale(self):
        return super(BaseHandler, self).get_user_locale()

    def write(self, chunk):
        super(BaseHandler, self).write(chunk)

    def write_error(self, status_code, **kwargs):
        """
        处理HTTP报错
        :param status_code:
        :param kwargs:
        :return:
        """
        print('heldld')
        if status_code == 404:
            self.render("error/404.html")
        # elif status_code == 500:
        #     self.render("500.html")
        # else:
        #     super(BaseHandler, self).write_error(status_code, **kwargs)
        super(BaseHandler, self).write_error(status_code, **kwargs)

    def on_finish(self):
        self.__process_session()     # 处理session
        try:
            # self.db.close_all()     # 关闭数据库连接

            self.db.remove()

        except:
            pass
        try:
            close_caches()          # 关闭cache连接
        except:
            pass
        super(BaseHandler, self).on_finish()

    def __get_session(self, _token):
        """
            获得session
        :param _token:
        :return:
        """
        if _token is None:
            session = SessionStore()
            session.create()
        else:
            session = SessionStore()
            if not session.exists(_token):
                session.create()
            else:
                session = SessionStore(_token)
            return session

    def __process_session(self):
        if self.session.modified:  # 如果session有被编辑过,则保存session
            if self.session.get_expire_at_brower_close():
                max_age = None
                expires = None
            else:
                max_age = self.session.get_expiry_age()
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
            if self._status_code != 500:
                self.session.save()
                self.set_cookie(self.application._cookie_name, self.session.session_key, max_age=max_age,
                                expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                                path=settings.SESSION_COOKIE_PATH,
                                secure=settings.SESSION_COOKIE_SECURE or None,
                                httponly=settings.SESSION_COOKIE_HTTPONLY or None
                                )
            self.session.modified = False


class MyErrorHandler(BaseHandler):
    """
    没有找到匹配的URL时,将调用ErrorHandler, 以此来自定义404.html页面.
    """
    def prepare(self):
        self.set_status(404)
        self.render('404.html')


class WebServiceHandler(BaseHandler):
    encoder_class = encoders.JSONEncoder

    def initialize(self):
        super(WebServiceHandler, self).initialize()

    def write(self, data):
        if data is None:
            return bytes()

        super(WebServiceHandler, self).write(json.dumps(data, cls=self.encoder_class))
        # 待明天更新!!!


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    encoder_class = encoders.JSONEncoder

    def __init__(self, application, request, **kwargs):
        print('hello')
        super(WebSocketHandler, self).__init__(application, request, **kwargs)

    def check_origin(self, origin):
        """是否检查跨域访问,

            返回False ---> 只允许域内访问
            返回True  ---> 允许跨域访问
        :param origin:
        :return:
        """
        return True

    def open(self, *args, **kwargs):
        super(WebSocketHandler, self).open(*args, **kwargs)

    def on_message(self, message):
        raise NotImplementedError('subclasses of WebSocketHandler must provide a on_message() method')

    def on_close(self):
        raise NotImplementedError('subclasses of WebSocketHandler must provide a on_close() method')

    def on_finish(self, *args, **kwargs):
        print('end..........')
